// Copyright (c) 2022 CHANGLEI. All rights reserved.

import 'dart:math';

import 'package:aircraft_war/bloc/bloc_listenable.dart';
import 'package:aircraft_war/bloc/game_score_cubit.dart';
import 'package:aircraft_war/bloc/game_state_cubit.dart';
import 'package:aircraft_war/commons/fonts.dart';
import 'package:aircraft_war/components/main_game.dart';
import 'package:flame/components.dart';
import 'package:flame/extensions.dart';
import 'package:flutter/cupertino.dart' as cupertino;

final _textPaint = TextPaint(
  style: const cupertino.TextStyle(
    color: cupertino.CupertinoColors.secondaryLabel,
    fontFamily: handwritten,
    fontSize: 18,
  ),
);
final _scorePaint = TextPaint(
  style: const cupertino.TextStyle(
    color: cupertino.CupertinoColors.label,
    fontFamily: handwritten,
    fontSize: 32,
    overflow: cupertino.TextOverflow.ellipsis,
  ),
);

const _promptText = '恭喜！您的最终成绩是';

final _promptSize = _textPaint.measureText(_promptText);

/// Created by changlei on 2022/5/24.
///
/// 截止分数
class ScoreText extends GameStatePositionComponent {
  late final _score = _Score();

  Vector2? _parentSize;

  @override
  Future<void> onLoad() async {
    onNewState(gameRef.stateCubit.state);
  }

  @override
  void render(Canvas canvas) {
    _textPaint.render(
      canvas,
      _promptText,
      Vector2(size.x / 2, 0),
      anchor: Anchor.topCenter,
    );
  }

  void _relayout() {
    if (_parentSize != null) {
      layout(_parentSize!);
    }
  }

  /// 布局
  void layout(Vector2 parentSize) {
    _parentSize = parentSize;
    _score.layout();
    size = Vector2(
      min(max(_promptSize.x, _score.width), parentSize.x),
      _promptSize.y + 10 + _score.height,
    );
    anchor = Anchor.topCenter;
    position = Vector2(parentSize.x / 2, parentSize.y * 0.23);
  }

  @override
  void onNewState(GameState state) {
    switch (state) {
      case GameState.idle:
      case GameState.pending:
      case GameState.running:
      case GameState.pausing:
        _score.removeFromParent();
        break;
      case GameState.stopped:
        add(_score);
        _relayout();
        break;
    }
  }
}

class _Score extends PositionComponent with BlocListenable<GameScoreCubit, int>, HasGameRef<MainGame> {
  late final _text = TextComponent(
    textRenderer: _scorePaint,
  );

  @override
  Future<void> onLoad() async {
    await add(_text);
    onNewState(gameRef.scoreCubit.state);
  }

  @override
  void onNewState(int state) {
    _text.text = state.toString();
    (parent as ScoreText?)?._relayout();
  }

  /// 布局
  void layout() {
    size = _text.size;
    anchor = Anchor.topCenter;
    position = Vector2(max(size.x, _promptSize.x) / 2, _promptSize.y + 10);
  }
}
